<template>
  <div class="safety-tech-bg">
    <div class="particle-bg"></div>
    <div class="safety-content-table">
      <div class="safety-header-bar">
        <div class="safety-title">
          <i class="el-icon-warning safety-icon"></i>
          <span>安全隐患上报</span>
        </div>
        <el-select v-model="selectedAreaId" placeholder="切换小区" @change="handleAreaChange" class="area-select" style="width: 180px;">
          <el-option v-for="area in areaList" :key="area.id" :label="area.aname" :value="area.id" />
        </el-select>
      </div>
      <el-button type="primary" @click="openDialog()" class="add-btn">新增隐患上报</el-button>
      <el-table :data="tableData" class="safety-table" stripe>
        <el-table-column type="index" :index="(index) => index + 1" label="编号" width="80" />
        <el-table-column prop="stName" label="安全隐患" />
        <el-table-column prop="state" label="状态" :formatter="formatStatus" />
        <el-table-column prop="amName" label="管理员" />
        <el-table-column prop="createTime" label="上报时间" :formatter="formatDateTime" />
        <el-table-column prop="dealTime" label="解决时间" :formatter="formatDateTime" />
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button size="small" @click="openDialog(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        style="margin-top: 16px"
        background
        layout="prev, pager, next, jumper, ->, total"
        :total="total"
        :page-size="pageSize"
        :current-page="currentPage"
        @current-change="handlePageChange"
      />
      <el-dialog :title="dialogTitle" v-model="dialogVisible" class="safety-dialog">
        <el-form :model="form" label-width="100px">
          <el-form-item label="安全隐患">
            <el-select v-model="form.sid" placeholder="请选择安全隐患类型" @change="handleSafetyTypeChange" clearable :disabled="safetyTypesLoading">
              <el-option v-for="type in safetyTypes" :key="type.sid" :label="`${type.stName}`" :value="type.sid" />
            </el-select>
            <div v-if="safetyTypesLoading" class="el-loading-text">加载中...</div>
            <div v-if="safetyTypesError" class="text-danger">{{ safetyTypesError }}</div>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="form.state" placeholder="请选择状态">
              <el-option label="未处理" :value="1"></el-option>
              <el-option label="已处理" :value="2"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="管理员">
            <el-select v-model="form.amId" placeholder="请选择管理员" @change="handleAdminChange" clearable :disabled="administratorsLoading">
              <el-option v-for="admin in administrators" :key="admin.amId" :label="`${admin.amName} `" :value="admin.amId" />
            </el-select>
            <div v-if="administratorsLoading" class="el-loading-text">加载中...</div>
            <div v-if="administratorsError" class="text-danger">{{ administratorsError }}</div>
          </el-form-item>
          <el-form-item label="上报时间">
            <el-date-picker
              v-model="form.createTime"
              type="datetime"
              placeholder="选择上报时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DDTHH:mm:ss"
            />
          </el-form-item>
          <el-form-item label="解决时间">
            <el-date-picker
              v-model="form.dealTime"
              type="datetime"
              placeholder="选择解决时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DDTHH:mm:ss"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>
<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessageBox } from 'element-plus';
import { postRequest, putRequest, deleteRequest, getRequest } from '@/utils/request';

const tableData = ref([]);
const total = ref(0);
const pageSize = ref(10);
const currentPage = ref(1);
const dialogVisible = ref(false);
const dialogTitle = ref('新增隐患上报');
const form = reactive({
  id: null,
  sid: '',
  stName: '',
  state: '',
  amId: '',
  amName: '',
  createTime: '',
  dealTime: ''
});
const safetyTypes = ref([]);
const administrators = ref([]);
const safetyTypesLoading = ref(false);
const administratorsLoading = ref(false);
const safetyTypesError = ref('');
const administratorsError = ref('');
const areaList = ref([]);
const selectedAreaId = ref('');

const formatStatus = (row, column, value) => {
  const statusMap = { 1: '未处理', 2: '已处理' };
  return statusMap[value] || value;
};
const formatDateTime = (row, column, value) => {
  if (!value) return '';
  const date = new Date(value);
  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}`;
};
function fetchAreaList() {
  getRequest('/area/getAreaLists').then(res => {
    if (res && res.data && Array.isArray(res.data.data)) {
      areaList.value = res.data.data;
      if (!selectedAreaId.value && areaList.value.length > 0) {
        selectedAreaId.value = areaList.value[0].id;
      }
    }
  });
}
function fetchSafetyTypes() {
  safetyTypesLoading.value = true;
  safetyTypesError.value = '';
  getRequest('/securityThreat/getSecurityThreatList').then(res => {
    if (res && res.data && Array.isArray(res.data.data)) {
      const validTypes = res.data.data
        .filter(element => element && element.id !== undefined)
        .map(element => ({
          sid: String(element.id),
          stName: element.stName || element.name || `隐患类型${element.id}`
        }));
      safetyTypes.value = validTypes;
      if (validTypes.length === 0) {
        safetyTypesError.value = '未找到安全隐患类型数据，请联系系统管理员';
      }
    } else {
      safetyTypesError.value = '安全隐患类型数据格式不正确';
      console.error('安全隐患类型数据格式错误:', res);
    }
  }).catch(error => {
    safetyTypesError.value = '获取安全隐患类型失败: ' + (error.message || '网络错误');
    console.error('获取安全隐患类型失败:', error);
  }).finally(() => {
    safetyTypesLoading.value = false;
  });
}
function fetchAdministrators() {
  administratorsLoading.value = true;
  administratorsError.value = '';
  getRequest('/areaManager/getAreaManagerList').then(res => {
    if (res && res.data && Array.isArray(res.data.data)) {
      const validAdmins = res.data.data
        .filter(element => element && element.id !== undefined)
        .map(element => ({
          amId: String(element.id),
          amName: element.amName || element.username || element.name || `管理员${element.id}`
        }));
      administrators.value = validAdmins;
      if (validAdmins.length === 0) {
        administratorsError.value = '未找到管理员数据，请联系系统管理员';
      }
    } else {
      administratorsError.value = '管理员数据格式不正确';
      console.error('管理员数据格式错误:', res);
    }
  }).catch(error => {
    administratorsError.value = '获取管理员列表失败: ' + (error.message || '网络错误');
    console.error('获取管理员列表失败:', error);
  }).finally(() => {
    administratorsLoading.value = false;
  });
}
function fetchData() {
  postRequest('/reportSafetyHazards/getReportSafetyHazardsByPage', { current: currentPage.value, size: pageSize.value, areaId: selectedAreaId.value }).then(res => {
    if (res && res.data) {
      tableData.value = Array.isArray(res.data.data.reportSafetyHazards) ? res.data.data.reportSafetyHazards : [];
      total.value = res.data.data.total || 0;
    } else {
      tableData.value = [];
      total.value = 0;
    }
  });
}
function openDialog(row) {
  if (row) {
    dialogTitle.value = '编辑隐患上报';
    Object.assign(form, row);
    form.sid = String(row.sid || '');
    form.amId = String(row.amId || row.amName || '');
    form.createTime = row.createTime || '';
    form.dealTime = row.dealTime || '';
    setTimeout(() => {
      handleSafetyTypeChange(form.sid);
      handleAdminChange(form.amId);
    }, 0);
  } else {
    dialogTitle.value = '新增隐患上报';
    form.id = null;
    form.sid = '';
    form.stName = '';
    form.state = '';
    form.amId = '';
    form.amName = '';
    form.createTime = '';
    form.dealTime = '';
  }
  dialogVisible.value = true;
}
function handleSafetyTypeChange(sid) {
  const selectedType = safetyTypes.value.find(type => type.sid === String(sid));
  if (selectedType) {
    form.stName = selectedType.stName;
  } else {
    form.stName = '';
  }
}
function handleAdminChange(amId) {
  const selectedAdmin = administrators.value.find(admin => admin.amId === String(amId));
  if (selectedAdmin) {
    form.amName = selectedAdmin.amName;
  } else {
    form.amName = '';
  }
}
function handleSubmit() {
  if (form.id) {
    putRequest('/reportSafetyHazards/updateReportSafetyHazardsById', form).then(() => {
      dialogVisible.value = false;
      fetchData();
    });
  } else {
    postRequest('/reportSafetyHazards/addReportSafetyHazards', form).then(() => {
      dialogVisible.value = false;
      fetchData();
    });
  }
}
function handleDelete(id) {
  ElMessageBox.confirm('确定要删除该记录吗？', '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteRequest(`/reportSafetyHazards/deleteReportSafetyHazardsById/${id}`).then(() => {
      fetchData();
    });
  }).catch(() => {});
}
function handlePageChange(page) {
  currentPage.value = page;
  fetchData();
}
function handleAreaChange() {
  fetchData();
}
onMounted(() => {
  fetchAreaList();
  fetchData();
  fetchSafetyTypes();
  fetchAdministrators();
});
</script>
<style scoped>
.safety-tech-bg {
  min-height: 100vh;
  background: linear-gradient(135deg, #23243a 0%, #3a3d5c 100%);
  position: relative;
  overflow: hidden;
  display: flex;
  align-items: flex-start;
  justify-content: center;
}
.particle-bg {
  position: absolute;
  top: 0; left: 0; right: 0; bottom: 0;
  z-index: 0;
  pointer-events: none;
  background: repeating-linear-gradient(135deg,rgba(56,189,248,0.08) 0 2px,transparent 2px 40px),
    repeating-linear-gradient(45deg,rgba(118,75,162,0.08) 0 2px,transparent 2px 40px);
  opacity: 0.7;
  animation: bgmove 30s linear infinite;
}
@keyframes bgmove {
  0% { background-position: 0 0, 0 0; }
  100% { background-position: 200px 200px, -200px -200px; }
}
.safety-content-table {
  position: relative;
  z-index: 2;
  background: rgba(40,50,90,0.96);
  border-radius: 24px;
  box-shadow: 0 8px 40px #38bdf855, 0 1.5px 8px #764ba255;
  padding: 36px 36px 32px 36px;
  min-width: 900px;
  max-width: 98vw;
  margin-top: 48px;
  border: 1.5px solid #38bdf8cc;
  backdrop-filter: blur(8px);
}
.safety-header-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}
.safety-title {
  display: flex;
  align-items: center;
  font-size: 26px;
  font-weight: 700;
  color: #38bdf8;
  letter-spacing: 2px;
  text-shadow: 0 2px 8px #38bdf855;
}
.safety-icon {
  font-size: 32px;
  margin-right: 14px;
  filter: drop-shadow(0 2px 8px #38bdf8cc);
}
.area-select {
  min-width: 180px;
  background: rgba(255,255,255,0.08);
  border-radius: 8px;
  color: #fff;
  border: 1.5px solid #38bdf8cc;
}
.add-btn {
  margin-bottom: 18px;
  background: linear-gradient(90deg,#38bdf8,#764ba2);
  border: none;
  font-weight: 600;
  letter-spacing: 1px;
  box-shadow: 0 2px 12px #38bdf855;
}
.add-btn:hover {
  background: linear-gradient(90deg,#764ba2,#38bdf8);
  color: #fff;
}
.safety-table {
  background: rgba(255,255,255,0.04);
  border-radius: 12px;
  box-shadow: 0 2px 12px #38bdf822;
}
.safety-dialog {
  border-radius: 18px;
  background: rgba(40,50,90,0.98);
}
.el-form-item {
  margin-bottom: 18px;
}
.el-select, .el-input, .el-date-picker {
  background: rgba(255,255,255,0.08);
  border-radius: 8px;
  color: #fff;
  border: 1.5px solid #38bdf8cc;
}
.el-input__inner, .el-select__inner {
  background: transparent;
  color: #fff;
}
.el-button--primary {
  background: linear-gradient(90deg,#38bdf8,#764ba2);
  border: none;
  font-weight: 600;
  letter-spacing: 1px;
  box-shadow: 0 2px 12px #38bdf855;
}
.el-button--primary:hover {
  background: linear-gradient(90deg,#764ba2,#38bdf8);
  color: #fff;
}
.text-danger {
  color: #ff6b6b;
  font-size: 13px;
  margin-top: 4px;
}
</style> 